<template>
  <div class="page-title-setting">
    <Input
      class="workflow-title-input"
      placeholder="请输入"
      v-model="name"
      @on-blur="setName"
      v-if="showInput"
      :maxlength="20"
    />
    <div class="workflow-title overflow" @click="showInput = true" :title="name" v-else>{{name}}</div>
  </div>
</template>

<script>
import { renameNode } from 'http/api/workflow';
import { mapMutations, mapState } from 'vuex';

export default {
  props: ['nodeInfo'],
  computed: {
    ...mapState({
      node: state => state.workflow.node
    })
  },

  watch: {
    nodeInfo () {
      this.name = (this.nodeInfo && this.nodeInfo.name) ? this.nodeInfo.name : '';
    }
  },

  data () {
    return {
      showInput: false,
      name: ''
    };
  },
  methods: {
    ...mapMutations(['setNode']),

    setName () {
      let { id, name } = this.nodeInfo;

      if (this.name === name) {
        this.showInput = false;
        return;
      }

      renameNode({
        name: this.name,
        pipelineTaskId: id
      })
        .then(res => {
          // 手动更新名称
          this.node[id].name = this.name;
          this.setNode(this.node);
          this.$Message.success('命名成功');

          this.showInput = false;
        })
        .catch(() => {
          this.showInput = false;
        });
    }
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
.page-title-setting {
  border-bottom: #dddddd 1px solid;
}
</style>
